package com.love.netty.demo.handler.response;

import com.love.netty.core.packet.request.LoginRequestPacket;
import com.love.netty.core.packet.response.LoginResponsePacket;
import com.love.netty.util.LoginUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName: LoginResponseHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-06-24 14:57
 **/
public class LoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(sdf.format(new Date()) + " 客户端准备开始登录");
        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUserName("flash");
        loginRequestPacket.setPassword("pwd");
        // 写数据
        ctx.channel().writeAndFlush(loginRequestPacket);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginResponsePacket loginResponsePacket) throws Exception {

        if (loginResponsePacket.isSuccess()) {
            LoginUtils.markAsLogin(channelHandlerContext.channel());
            System.out.println(sdf.format(new Date()) + ": 客户端登录成功");
        } else {
            System.out.println(sdf.format(new Date())+ ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
        }
    }
}
